package 网络编程;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPDemo2 {
    public static void main(String[] args) throws IOException {
        //通过UDP接收数据


        //1.创建DatagramSocket对象
        //细节:在接收数据的时候,一定要绑定端口,而且绑定的端口一定要跟发送的端口一致
        DatagramSocket ds=new DatagramSocket(10086);
        //2.接收数据
        //创建一个箱子用来接收
        byte[] bytes=new byte[1024];
        DatagramPacket dp=new DatagramPacket(bytes, bytes.length);
        ds.receive(dp);
        //解析数据包
        byte[] data = dp.getData();
        int port = dp.getPort();
        int length = dp.getLength();
        InetAddress address = dp.getAddress();
        System.out.println("接收到的数据是:"+new String(data,0, length));
        System.out.println("该数据是从IP为:"+address+"端口为:"+port+"发出来的");
        //释放资源
        ds.close();
    }
}
